<template>
  <view class="register-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- Logo和标题区域 -->
      <view class="header-section">
        <view class="logo-container float-animation">
          <u-icon name="account-fill" color="#667eea" size="60"></u-icon>
        </view>
        <text class="app-title animated-gradient-text">加入我们</text>
        <text class="app-subtitle">创建您的社交圈子账户</text>
      </view>

      <!-- 注册表单 -->
      <view class="form-container glass-card">
        <view class="form-header">
          <text class="form-title">创建新账户</text>
          <text class="form-subtitle">请填写以下信息完成注册</text>
        </view>

        <view class="form-content">
          <!-- 用户名输入框 -->
          <view class="input-group">
            <view class="input-label">
              <u-icon name="account" color="#667eea" size="18"></u-icon>
              <text class="label-text">用户名</text>
            </view>
            <u-input
              v-model="registerForm.username"
              placeholder="请输入用户名"
              class="modern-input"
              border="none"
              :custom-style="inputStyle"
              @blur="validateUsername"
            />
            <text v-if="errors.username" class="error-text">{{ errors.username }}</text>
          </view>

          <!-- 密码输入框 -->
          <view class="input-group">
            <view class="input-label">
              <u-icon name="lock" color="#667eea" size="18"></u-icon>
              <text class="label-text">密码</text>
            </view>
            <u-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码"
              class="modern-input"
              border="none"
              :custom-style="inputStyle"
              @blur="validatePassword"
            />
            <text v-if="errors.password" class="error-text">{{ errors.password }}</text>
          </view>

          <!-- 确认密码输入框 -->
          <view class="input-group">
            <view class="input-label">
              <u-icon name="lock-fill" color="#667eea" size="18"></u-icon>
              <text class="label-text">确认密码</text>
            </view>
            <u-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              class="modern-input"
              border="none"
              :custom-style="inputStyle"
              @blur="validateConfirmPassword"
            />
            <text v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</text>
          </view>

          <!-- 验证码输入框 -->
          <view class="input-group" v-if="captchaEnabled">
            <view class="input-label">
              <u-icon name="shield" color="#667eea" size="18"></u-icon>
              <text class="label-text">验证码</text>
            </view>
            <view class="captcha-container">
              <u-input
                v-model="registerForm.code"
                placeholder="请输入验证码"
                class="modern-input captcha-input"
                border="none"
                :custom-style="inputStyle"
              />
              <image 
                class="captcha-image" 
                :src="codeUrl" 
                @click="getCode"
              />
            </view>
          </view>

          <!-- 用户协议 -->
          <view class="agreement-section">
            <u-checkbox-group v-model="agreeTermsGroup">
              <u-checkbox
                name="agreeTerms"
                active-color="#667eea"
                size="16"
                @change="handleAgreeTermsChange"
              >
                <text class="agreement-text">我已阅读并同意</text>
              </u-checkbox>
            </u-checkbox-group>
            <text class="agreement-link" @click="handleUserAgreement">《用户协议》</text>
            <text class="agreement-text">和</text>
            <text class="agreement-link" @click="handlePrivacy">《隐私政策》</text>
          </view>

          <!-- 注册按钮 -->
          <button 
            class="gradient-button register-btn"
            :class="{ 'loading': loading }"
            @click="handleRegister"
            :disabled="loading || !agreeTerms"
          >
            <u-loading-icon v-if="loading" color="white" size="20"></u-loading-icon>
            <text class="button-text">{{ loading ? '注册中...' : '立即注册' }}</text>
          </button>

          <!-- 登录链接 -->
          <view class="login-section">
            <text class="login-text">已有账户？</text>
            <text class="login-link" @click="handleLogin">立即登录</text>
          </view>
        </view>
      </view>

      <!-- 注册优势 -->
      <view class="features-section">
        <view class="feature-item">
          <u-icon name="heart-fill" color="rgba(255,255,255,0.8)" size="20"></u-icon>
          <text class="feature-text">发现有趣的圈子</text>
        </view>
        <view class="feature-item">
          <u-icon name="chat-fill" color="rgba(255,255,255,0.8)" size="20"></u-icon>
          <text class="feature-text">与志同道合的人交流</text>
        </view>
        <view class="feature-item">
          <u-icon name="star-fill" color="rgba(255,255,255,0.8)" size="20"></u-icon>
          <text class="feature-text">分享精彩生活瞬间</text>
        </view>
      </view>
    </view>

    <!-- Toast提示 -->
  </view>
</template>

<script>
import { getCodeImg, register } from "@/api/login"

export default {
  data() {
    return {
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        code: '',
        uuid: ''
      },
      loading: false,
      captchaEnabled: true,
      codeUrl: '',
      agreeTerms: false,
      agreeTermsGroup: [],
      errors: {},
      inputStyle: {
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
        borderRadius: '15px',
        padding: '15px 20px',
        fontSize: '16px',
        border: '2px solid rgba(102, 126, 234, 0.1)'
      }
    }
  },
  created() {
    this.getCode()
  },
  methods: {
    // 获取验证码
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = 'data:image/gif;base64,' + res.img
          this.registerForm.uuid = res.uuid
        }
      })
    },
    
    // 表单验证
    validateUsername() {
      if (!this.registerForm.username) {
        this.errors.username = '请输入用户名'
        return false
      }
      if (this.registerForm.username.length < 2) {
        this.errors.username = '用户名至少2个字符'
        return false
      }
      if (this.registerForm.username.length > 20) {
        this.errors.username = '用户名不能超过20个字符'
        return false
      }
      // 检查用户名格式（字母、数字、下划线）
      const usernameRegex = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/
      if (!usernameRegex.test(this.registerForm.username)) {
        this.errors.username = '用户名只能包含字母、数字、下划线和中文'
        return false
      }
      this.errors.username = ''
      return true
    },
    
    validatePassword() {
      if (!this.registerForm.password) {
        this.errors.password = '请输入密码'
        return false
      }
      if (this.registerForm.password.length < 6) {
        this.errors.password = '密码至少6个字符'
        return false
      }
      if (this.registerForm.password.length > 20) {
        this.errors.password = '密码不能超过20个字符'
        return false
      }
      // 检查密码强度（至少包含字母和数字）
      const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]+$/
      if (!passwordRegex.test(this.registerForm.password)) {
        this.errors.password = '密码必须包含字母和数字'
        return false
      }
      this.errors.password = ''
      return true
    },
    
    validateConfirmPassword() {
      if (!this.registerForm.confirmPassword) {
        this.errors.confirmPassword = '请确认密码'
        return false
      }
      if (this.registerForm.password !== this.registerForm.confirmPassword) {
        this.errors.confirmPassword = '两次输入的密码不一致'
        return false
      }
      this.errors.confirmPassword = ''
      return true
    },
    
    // 注册处理
    async handleRegister() {
      // 表单验证
      const isUsernameValid = this.validateUsername()
      const isPasswordValid = this.validatePassword()
      const isConfirmPasswordValid = this.validateConfirmPassword()
      
      if (!isUsernameValid || !isPasswordValid || !isConfirmPasswordValid) {
        this.showToast('请检查输入信息', 'error')
        return
      }
      
      if (this.captchaEnabled && !this.registerForm.code) {
        this.showToast('请输入验证码', 'error')
        return
      }
      
      if (!this.agreeTerms) {
        this.showToast('请先同意用户协议和隐私政策', 'error')
        return
      }
      
      this.loading = true
      
      try {
        const res = await register(this.registerForm)
        
        if (res.code === 200) {
          this.showToast('注册成功', 'success')
          
          // 显示成功提示并跳转
          setTimeout(() => {
            uni.showModal({
              title: '注册成功',
              content: `恭喜您，账号 ${this.registerForm.username} 注册成功！`,
              showCancel: false,
              confirmText: '去登录',
              success: () => {
                this.$tab.redirectTo('/pages/login')
              }
            })
          }, 1500)
        } else {
          this.showToast(res.msg || '注册失败', 'error')
          if (this.captchaEnabled) {
            this.getCode()
          }
        }
      } catch (error) {
        console.error('注册错误:', error)
        this.showToast('网络错误，请稍后重试', 'error')
        if (this.captchaEnabled) {
          this.getCode()
        }
      } finally {
        this.loading = false
      }
    },

    // 处理用户协议变化
    handleAgreeTermsChange(e) {
      this.agreeTerms = e.includes('agreeTerms')
    },
    
    // 跳转登录
    handleLogin() {
      this.$tab.navigateTo('/pages/login')
    },
    
    // 用户协议
    handleUserAgreement() {
      const globalConfig = getApp().globalData.config
      if (globalConfig.appInfo.agreements && globalConfig.appInfo.agreements[1]) {
        const site = globalConfig.appInfo.agreements[1]
        this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
      } else {
        this.showToast('用户协议页面开发中', 'info')
      }
    },
    
    // 隐私政策
    handlePrivacy() {
      const globalConfig = getApp().globalData.config
      if (globalConfig.appInfo.agreements && globalConfig.appInfo.agreements[0]) {
        const site = globalConfig.appInfo.agreements[0]
        this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
      } else {
        this.showToast('隐私政策页面开发中', 'info')
      }
    },
    
    // 显示提示
    showToast(title, type = 'default') {
      // 使用 uView 2.0 的 toast 方法
      this.$u.toast(title)
    }
  }
}
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
  position: relative;
  overflow: hidden;
}

.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
  
  .circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    
    &.circle-1 {
      width: 180px;
      height: 180px;
      top: -90px;
      left: -90px;
      animation: float 8s ease-in-out infinite;
    }
    
    &.circle-2 {
      width: 120px;
      height: 120px;
      bottom: -60px;
      right: -60px;
      animation: float 6s ease-in-out infinite reverse;
    }
    
    &.circle-3 {
      width: 80px;
      height: 80px;
      top: 40%;
      right: -40px;
      animation: float 10s ease-in-out infinite;
    }
  }
}

.main-content {
  position: relative;
  z-index: 1;
  padding: 40px 30px 30px;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header-section {
  text-align: center;
  margin-bottom: 30px;
  
  .logo-container {
    margin-bottom: 20px;
  }
  
  .app-title {
    font-size: 32px;
    font-weight: bold;
    display: block;
    margin-bottom: 8px;
  }
  
  .app-subtitle {
    font-size: 16px;
    color: rgba(255, 255, 255, 0.8);
  }
}

.form-container {
  flex: 1;
  margin-bottom: 20px;
  
  .form-header {
    text-align: center;
    margin-bottom: 25px;
    
    .form-title {
      font-size: 24px;
      font-weight: 600;
      color: #333;
      display: block;
      margin-bottom: 8px;
    }
    
    .form-subtitle {
      font-size: 14px;
      color: #666;
    }
  }
  
  .form-content {
    .input-group {
      margin-bottom: 18px;
      
      .input-label {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        
        .label-text {
          margin-left: 8px;
          font-size: 14px;
          color: #333;
          font-weight: 500;
        }
      }
      
      .error-text {
        font-size: 12px;
        color: #ff4757;
        margin-top: 5px;
        margin-left: 5px;
      }
    }
    
    .captcha-container {
      display: flex;
      align-items: center;
      gap: 10px;
      
      .captcha-input {
        flex: 1;
      }
      
      .captcha-image {
        width: 100px;
        height: 50px;
        border-radius: 8px;
        border: 1px solid #e0e0e0;
      }
    }
    
    .agreement-section {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      margin: 20px 0;
      line-height: 1.5;
      
      .agreement-text {
        font-size: 13px;
        color: #666;
        margin: 0 3px;
      }
      
      .agreement-link {
        font-size: 13px;
        color: #667eea;
        font-weight: 500;
        margin: 0 2px;
      }
    }
    
    .register-btn {
      width: 100%;
      margin: 25px 0 20px;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      
      &:disabled {
        opacity: 0.6;
        background: #ccc !important;
      }
      
      &.loading {
        opacity: 0.8;
      }
      
      .button-text {
        margin-left: 8px;
      }
    }
    
    .login-section {
      text-align: center;
      
      .login-text {
        font-size: 14px;
        color: #666;
      }
      
      .login-link {
        font-size: 14px;
        color: #667eea;
        font-weight: 500;
        margin-left: 5px;
      }
    }
  }
}

.features-section {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
  
  .feature-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .feature-text {
      font-size: 12px;
      color: rgba(255, 255, 255, 0.8);
      margin-top: 8px;
      text-align: center;
    }
  }
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20px); }
}
</style>